var app = getApp();
Page({
  data: {
    det_data: {},
    data_url: "",
    modalFrame: false,
    modal_number: 1,
    options: {},
    collageList: [],
    icon_num: "",
    buy_car_show: true,
    immbuy_show: true
  },

  onLoad: function (options) {
    var that = this;
    this.setData({
      data_url: app.globalData.data_url
    })
    this.setData({
      options: options
    })
    wx.request({
      url: that.data.data_url + "/GPD/getcommoditybyid.do",
      data: {
        commodityid: options.id
      },
      success: function (res) {
        res.data.price = res.data.price.toFixed(2)
        that.setData({
          det_data: res.data
        })
      }
    })
    wx.request({
      url: that.data.data_url + '/GPD/getCommodityCollage.do',
      data: {
        commodity_id: options.id
      },
      success: function (res) {
        var now = new Date().getTime()
        function chekfinish(item) {
          var surplus = item.enddate - now
          return surplus > 0
        }
        res.data.collage = res.data.collage.filter(chekfinish).map(function (item, i) {
          var surplus = item.enddate - now
          if (surplus <= 0) {
            index.push(i)
          }
          var hour = Math.floor(surplus / 1000 / 3600);
          var min = Math.floor(surplus / 1000 / 60) % 60;
          var sec = Math.floor(surplus / 1000) % 60;
          item.hour = hour + 1 <= 10 ? '0' + hour : hour
          item.min = min + 1 <= 10 ? '0' + min : min
          item.sec = sec + 1 <= 10 ? '0' + sec : sec
          return item
        })
        that.setData({
          collageList: res.data.collage
        })
        if (res.data.collage.length > 0) {
          var timer = setInterval(function () {
            now = new Date().getTime()
            var collageList = that.data.collageList.filter(chekfinish).map(function (item, i) {
              var surplus = item.enddate - now
              if (surplus <= 0) {
                index.push(i)
              }
              var hour = Math.floor(surplus / 1000 / 3600);
              var min = Math.floor(surplus / 1000 / 60) % 60;
              var sec = Math.floor(surplus / 1000) % 60;
              item.hour = hour + 1 <= 10 ? '0' + hour : hour
              item.min = min + 1 <= 10 ? '0' + min : min
              item.sec = sec + 1 <= 10 ? '0' + sec : sec
              return item
            })
            if (collageList.length == 0) {
              clearTimeout(timer)
            }
            that.setData({
              collageList: collageList
            })
          }, 1000)
        }
      }
    })

    wx.connectSocket({
      url: 'wss://www.ynny168.com/GPD/collage-WebSocket/' + options.id
    })
    wx.onSocketMessage(function (res) {
      var data = JSON.parse(res.data)
      var collageList = that.data.collageList
      collageList.forEach(function (item, index) {
        if (data.id == item.id) {
          collageList[index].now_num = data.now_num
        }
      })
      wx.showModal({
        title: '数据变化',
        content: collageList,
      })
      that.setData({
        collageList: collageList
      })
    })
  },
  modalFrameShow: function () {
    var that = this;
    that.setData({
      modalFrame: true
    })
  },
  modalFrameHidden: function () {
    var that = this;
    that.setData({
      modalFrame: false,
      buy_car_show: true,
      immbuy_show: true
    })
  },
  immbuy: function (data) {
    var that = this;
    that.setData({
      buy_car_show: false
    })
    if (!that.data.modalFrame) {
      that.modalFrameShow()
    } else {
      that.goBuy(data)
    }
  },
  numberAdd: function () {
    this.setData({
      modal_number: ++this.data.modal_number
    })
  },
  numberMinus: function () {
    if (this.data.modal_number < 2) {
      this.setData({
        modal_number: 1
      })
    } else {
      this.setData({
        modal_number: (this.data.modal_number - 1)
      })
    }
  },
  addCarAndHiddenImmbuy: function () {
    var that = this
    that.setData({
      immbuy_show: false
    })
    if (!that.data.modalFrame) {
      that.modalFrameShow()
    } else {
      that.addBuyCar();
    }
  },
  addBuyCar: function () {
    wx.request({
      url: app.globalData.data_url + '/GPD/getCommodityStock.do',
      data: {
        commodity_id: this.data.det_data.id
      },
      success: res => {
        if (res.data.stock >= this.data.modal_number) {
          let cardata = wx.getStorageSync('carData') || []
          var arr1 = {
            num: this.data.modal_number,
            title: this.data.det_data.commodityname,
            price: this.data.det_data.price,
            id: this.data.det_data.id,
            image: this.data.det_data.bosimgurl[0],
            enableInterPay: this.data.det_data.integralpurchase,
            stock: this.data.det_data.stock,
            selected: true
          };
          let index = cardata.findIndex(item => {
            return item.id == this.data.det_data.id
          })
          if (index >= 0) {
            cardata[index].num++
          } else {
            cardata.push(arr1)
          }
          wx.setStorageSync('carData', cardata)
          wx.showToast({
            title: '已加入购物车',
          })
          this.setData({
            icon_num: cardata.length
          })
          this.setData({
            modalFrame: false,
            immbuy_show:true
          })
        } else {
          wx.showToast({
            title: '已售罄',
            image: '/images/close.png'
          })
        }
      }
    })

  },
  goBuy: function (data) {
    var that = this;
    wx.request({
      url: app.globalData.data_url + '/GPD/getCommodityStock.do',
      data: {
        commodity_id: this.data.det_data.id
      },
      success: res => {
        if (res.data.stock >= this.data.modal_number) {
          var i = 0;
          var arr1 = {
            num: this.data.modal_number,
            title: this.data.det_data.commodityname,
            id: this.data.det_data.id,
            price: data.id ? data.price : this.data.det_data.price,
            image: this.data.det_data.bosimgurl[0],
            stock: this.data.det_data.stock,
            enableInterPay: this.data.det_data.integralpurchase,
            selected: true
          };
          app.buyCar = [arr1]
          if (data.id) {
            wx.navigateTo({
              url: '/pages/orders/orders?data=' + JSON.stringify(data),
            })
            return
          }
          wx.navigateTo({
            url: '/pages/orders/orders',
          })
        } else {
          wx.showToast({
            title: '库存不足',
            image: '/images/close.png'
          })
        }
      }
    })
  },

  /**
   * 打开拼团
   * @type method
   */
  openGroup: function () {
    var that = this
    var collageList = this.data.collageList
    var itemList = collageList.map(function (item) {
      return item.peoplenum + '人团(￥' + item.price.toFixed(2) + ')'
    })
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        console.log(collageList[res.tapIndex])
        that.goBuy(collageList[res.tapIndex])
      }
    })
  },

  onReady: function () {

  },
  onShow: function () {
    this.setData({
      icon_num: wx.getStorageSync('carData').length
    })
  },
  onShareAppMessage: function () { },
  onUnload: function () {
    wx.closeSocket()
  },
})
